package cn.sinata.wanglin.database;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;

public class ProvinceDao {
	private DBMyHelper mDBHelper;
	public ProvinceDao(Context context){
		mDBHelper=DBMyHelper.getInstance(context);
	}
	/**
	 * 判断表是否存在
	 * @param /db
	 * @param tableName
	 * @return
	 */
	public boolean tabbleIsExist(String tableName) {
		SQLiteDatabase db=mDBHelper.getWritableDatabase();
		if (db==null || !db.isOpen()) {
			return false;
		}
		boolean result = false;
		if (tableName == null) {
			return false;
		}
		Cursor cursor = null;
		try {
			String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='"
					+ tableName.trim() + "' ";
			cursor = db.rawQuery(sql, null);
			if (cursor.moveToNext()) {
				int count = cursor.getInt(0);
				if (count > 0) {
					result = true;
				}
			}

		} catch (Exception e) {
		}finally {
			if (cursor != null) {
				cursor.close();
			}
		}
		return result;
	}
	public List<ProvinceInfo> getAllProvinceInfoByDB(JavaListBeanCallBack<ProvinceInfo> mCallBack){
		List<ProvinceInfo> mProvinceInfos=new ArrayList<ProvinceInfo>();
	    String table="province";
		if (tabbleIsExist(table)) {
			SQLiteDatabase db=mDBHelper.getWritableDatabase();
			if (db!=null && db.isOpen()) {
				Cursor cursor=db.rawQuery("select * from " + table, null);
				while (cursor.moveToNext()) {
					int province_id = cursor.getInt(cursor.getColumnIndex("province_id"));
					String province_name=cursor.getString(cursor.getColumnIndex("province_name"));
					ProvinceInfo mProvinceInfo=new ProvinceInfo(province_id, province_name);
					
					mProvinceInfos.add(mProvinceInfo);
				}
				cursor.close();
				mCallBack.onresult(1, mProvinceInfos, "");
			}
		}
		return mProvinceInfos;
	}
}
